const Router = require('koa-router')
const fs = require('fs')
const thunkify = require('thunkify')
const oss = require('../modules/oss')
const cdn = require('../modules/cdn')

const router = new Router({
  prefix: '/v1',
})

router.get('/', function* () {
  const key = 'json/status.json'
  let json = yield thunkify(fs.readFile)(`./${key}`)
  let newStatus = false
  if (this.query.run === 'yes') newStatus = true
  const fileContent = JSON.parse(json.toString())
  const currentStatus = fileContent.run
  if (newStatus != currentStatus) {
    const newFileContent = JSON.stringify({
      run: newStatus
    })
    yield thunkify(fs.writeFile)(`./${key}`, newFileContent)
    json = yield thunkify(fs.readFile)(`./${key}`)
  }
  const options = {
    Bucket: process.env.BUCKET,
    Key: key,
    Body: json,
    AccessControlAllowOrigin: '',
    ContentType: 'application/json',
    CacheControl: 'no-cache',
    ContentDisposition: '',
    ContentEncoding: 'utf-8',
    ServerSideEncryption: 'AES256',
    Expires: null,
  }
  const rs = yield thunkify(oss.putObject.bind(oss))(options)
  yield thunkify(cdn.refreshObjectCaches.bind(cdn))({
    ObjectType: 'File',
    ObjectPath: `${process.env.DOMAIN_NAME}${key}`,
  })
  this.body = rs
})

module.exports = router